package com.edu.demo.utils;

import com.edu.demo.config.CommonConfig;
import com.edu.demo.controller.CommonController;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * @ClassName: FileUtils
 * @Description:
 * @Author: zhaozhongda
 * @Date: 2023-01-18
 */

public class FileUtils {

    private static int DEFAULT_FILE_SIZE = 100*1024*1024;//100M

    private static  String[] projectPhotos = new String[]{
            "https://img2.baidu.com/it/u=271741156,1232068650&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500",
            "https://www.ccnustp.com/u/cms/jdzn/202108/181346169t0w.jpg",
            "https://www.tongruijiu.com/uploads/allimg/210905/2-210Z51R203433.jpg",
            "https://x0.ifengimg.com/res/2020/DE05B82EC5F45F090D03AF5A01266BDFDA8E1282_size107_w1080_h511.jpeg",
            "https://pic.rmb.bdstatic.com/bjh/down/9fc867b794553ca9b97f5222164e05c8.jpeg@wm_2,t_55m+5a625Y+3L+aVsOivtDEyMw==,fc_ffffff,ff_U2ltSGVp,sz_30,x_19,y_19",
            "https://p1.ssl.cdn.btime.com/t0100875d6b2621e8a7.jpg?size=530x453",
            "https://img2.baidu.com/it/u=3737695393,2686900715&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=480",
            "https://cbgccdn.thecover.cn/da225cbc-04a6-48f3-9a82-7b350cfda708_1646136580490",
            "https://n.sinaimg.cn/translate/201/w1080h721/20200508/2244-iteyfww5664437.jpg",
            "https://preview.qiantucdn.com/ing/20/58/13/64c58PICg4Fn6a7rqgBRX_PIC2018.jpg%21w1024_new_small"
    };

    /**
     * 允许上传的文件
     */
    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png",
            // word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // 视频格式
            "mp4", "avi", "rmvb",
            // pdf
            "pdf" };

    /**
     * 保存文件
     * @param file
     * @param path
     * @return
     * @throws IOException
     */
    public static String upload(MultipartFile file,String path) throws IOException {
        int length = Objects.requireNonNull(file.getOriginalFilename()).length();
        if(length > 100){
            throw new IOException("文件名长度超出100！");
        }

        assertAllowed(file);

        return uploadFile(file,path);

    }

    /**
     * 验证文件是否合法
     * @param file
     * @throws FileSizeLimitExceededException
     * @throws IOException
     */
    public static final void assertAllowed(MultipartFile file) throws FileSizeLimitExceededException,IOException {
        long size = file.getSize();
        if(size > DEFAULT_FILE_SIZE){ //大于100M
            throw new FileSizeLimitExceededException("文件大于100M!",DEFAULT_FILE_SIZE/1024/1024,DEFAULT_FILE_SIZE);
        }

        String extension = getExtension(file),fileName = file.getOriginalFilename();

        for (String s : DEFAULT_ALLOWED_EXTENSION) {
            if(s.equals(extension)) return;
        }

        throw new IOException("不允许上传该类型的文件");
    }

    /**
     * 获取文件的后缀名
     * @param file
     * @return
     */
    public final static String getExtension(MultipartFile file){
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if(Strings.isEmpty(extension)){
            extension = extensionName(file);
        }
        return extension;
    }

    /**
     * 通过文件内容类型获取文件后缀名
     * @param file
     * @return
     */
    private final static String extensionName(MultipartFile file){
        switch (file.getContentType()){
            case "image/png": return "png";
            case "image/jpg": return "jpg";
            case "image/jpeg": return "jpeg";
            case "image/bmp": return "bmp";
            case "image/gif": return "gif";
            default: return "";
        }
    }

    private final static String uploadFile(MultipartFile file, String path) throws IOException {
        Date now = new Date();
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
        String time = format.format(now);
        String absPath = path + time; //文件夹D://kkyy//2022//12//25
        File f1 = new File(absPath);
        String child = now.getMinutes() + now.getSeconds() + file.getOriginalFilename();

        if(!f1.exists()&& !f1.isDirectory()) {
            f1.mkdirs();
        }
        file.transferTo(new File(f1, child));

        return  time + child; //格式: 2022/12/25/文件名
    }

    /**
     * 获取文件类型
     * <p>
     * 例如: ruoyi.txt, 返回: txt
     *
     * @param fileName 文件名
     * @return 后缀（不含".")
     */
    public static String getFileType(String fileName)
    {
        int separatorIndex = fileName.lastIndexOf(".");
        if (separatorIndex < 0)
        {
            return "";
        }
        return fileName.substring(separatorIndex + 1).toLowerCase();

    }

    /**
     *
     * @param fileName yyyy/MM/dd/a.pdf
     * @param basePath E://A//education
     * @param originFileName  张三简历.pdf
     * @param response
     * @throws IOException
     */
    public static void downLoad(String fileName,String basePath,String originFileName, HttpServletResponse response) throws IOException {
        String fileType = getFileType(fileName);
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader(
                "Content-disposition",
                "attachment; filename="+originFileName+fileType);
        try(
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(basePath+fileName));
                // 输出流
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        ){
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        }
    }

    public static String photoInCache(){
        Random rd=new Random();  //创建实例

        int num=rd.nextInt(projectPhotos.length-1)+1;
        return projectPhotos[num];
    }

}
